package com.wechat.mp.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author Edward
 */
@AllArgsConstructor
@Controller
@Slf4j
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {
    private final WxMpService wxService;
    private final WxMpServiceHttpClientImpl wxMpServiceHttpClientImpl;
    private final JedisPool jedisPool;

    @RequestMapping("/greet")
    public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            map.put("user", user);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return "greet_user";
    }

    /**
     * 获取AccessToken
     * @param appid
     * @return
     */
    @RequestMapping("/getAccessToken")
    public String getAccessToken(@PathVariable String appid) {
        WxMpConfigStorage config = wxService.getWxMpConfigStorage();
        String accessToken = config.getAccessToken();
        // accessToken为空或者过期则重新获取
        if(accessToken == null || config.isAccessTokenExpired()){
            try {
                accessToken = wxMpServiceHttpClientImpl.getAccessToken(true);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        log.info("当前时间:"+System.currentTimeMillis()+"过期时间："+config.getExpiresTime());
        log.info("accessToken获取:"+accessToken);

        Jedis jedis = jedisPool.getResource();
//        jedis.set("test","hello redis");
        String test = jedis.get("test");

        return "";
    }
}
